#include "dialog_signin.h"
#include "ui_dialog_signin.h"
#include "pub_var.h"
#include <QDebug>

Dialog_signin::Dialog_signin(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_signin)
{
    ui->setupUi(this);
    errorCount = 0;
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    ui->leUserCode->setFocus();
}

Dialog_signin::~Dialog_signin()
{
    delete ui;
}
void Dialog_signin::on_pbOk_clicked()
{
    if(ui->leUserCode->text().trimmed().isEmpty() ||
            ui->lePassword->text().trimmed().isEmpty() ){
        return;
    }
    qrm->prepare("select e.empl_code, e.empl_name, e.dept_code, d.dept_name "
                 "from com_employee e, clinic.com_department d where e.dept_code = d.dept_code"
                 " and e.empl_code = :epcd and pswd = md5(:pswd)");
    qrm->bindValue(":epcd",ui->leUserCode->text());
    qrm->bindValue(":pswd",ui->lePassword->text());

    qrm->exec();
    if(qrm->next()){
        pub::usr_code = qrm->value(0).toString();
        pub::usr_name = qrm->value(1).toString();
        pub::dp_code = qrm->value(2).toString();
        pub::dp_name = qrm->value(3).toString();
        pub::userValidated = true;

        /**/
        qro->exec("select sid,serial# from v$session "
                  "where audsid = (select userenv('SESSIONID') From DUAL)");
        qro->next();
        QString sid = qro->value(0).toString();
        QString serial = qro->value(1).toString();

        qro->exec("SELECT SEQ_COM_LOGINSESSION.NEXTVAL FROM DUAL");
        qro->next();
        pub::LOGINSESSION = qro->value(0).toString();

        qro->prepare("insert into com_loginlog (log_index, empl_code, empl_name,login_date,"
                  " dept_code, dept_name, sid, serial) values(:log_index, :empl_code, "
                  ":empl_name, sysdate, :dept_code, :dept_name, :sid, :serial)");
        qro->bindValue(":log_index", pub::LOGINSESSION);
        qro->bindValue(":empl_code", pub::usr_code);
        qro->bindValue(":empl_name", pub::usr_name);
        qro->bindValue(":dept_code", pub::dp_code);
        qro->bindValue(":dept_name", pub::dp_name);
        qro->bindValue(":sid", sid);
        qro->bindValue(":serial", serial);
        qro->exec();

        this->close();
    }else{
        errorCount ++;
        if(errorCount > 2){
            pub::userValidated = false;
            this->close();
        }
    }
}

void Dialog_signin::on_pbCancel_clicked()
{
    pub::userValidated = false;
    this->close();
}

void Dialog_signin::on_leUserCode_returnPressed()
{
    if(ui->leUserCode->text().trimmed().isEmpty()){
        return;
    }else{
        ui->lePassword->setFocus();
    }
}

void Dialog_signin::on_lePassword_returnPressed()
{
    if(ui->lePassword->text().trimmed().isEmpty()){
        return;
    }else{
        ui->pbOk->setFocus();
    }
}
